// pages/open_info/detailInfo/detailInfo.js
var aliyun_api = require('../../../utils/aliyun-api-gateway.js');
var util = require('../../../utils/util.js');
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // delBtnWidth:320,    // 左滑宽度
    delBtnWidth: 160,    // 左滑宽度
    title: null,        // 页面标题
    text: null,         // '指纹' '密码' '门卡'
    devInfo: [],        // DevInfo数据结构，设备信息，包含'指纹' '密码' '门卡'三种
    devIndex: 0,        // 当前页面显示的设备信息下标
    showList: [],       // 显示列表，包括主内容，备注，左滑关联标识，当前列表下标对应的真正detailInfo里的下标
    isScroll: true,     // scroll-view y轴是否能编辑
    listIndex: 0,       // 当前页面的列表下标
    curbackup: '',      // 当前编辑框输入的备注信息
    showModal: false,   // 编辑框显示标识
    color: '',          // 编辑框确认按钮颜色
    showText: '',       // 编辑框弹出后默认显示
    productKey: '',
    deviceName: '',
    default: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this

    that.setData({
     productKey: options.productKey,
     deviceName: options.deviceName
    })
    var title = ['指纹', '密码', '门卡']
    
    var tmpDevInfo = wx.getStorageSync('deviceInfo')
    that.setData({
      devInfo: tmpDevInfo,
      devIndex: options.index,
      title: title[options.index] + '详情',
      text: title[options.index]
    })
    // console.log(tmpDevInfo)
    var tmpList = []
    var tmpArray = tmpDevInfo.deviceInfo[options.index].detailInfo
    if (tmpDevInfo.deviceInfo[options.index].usedNum === 0) {
      that.setData({
        default: true
      })
    } else {
      that.setData({
        default: false
      })
    }
    var index = 0
    for (let i = 0; i < tmpArray.length; i++) {
      if (tmpArray[i].data) {
        tmpList[index] = {
          'content': i,
          'backup': tmpArray[i].backup,
          'right': 0,
          'trueIndex': i,
          'userLimit': tmpArray[i].userLimit
        }
        index ++
      }
    }
    that.setData({
      showList: tmpList
    })
    console.log(that.data.showList)
    wx.setNavigationBarTitle({
      title: that.data.title
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  drawStart: function (e) {
    // console.log("drawStart");
    var touch = e.touches[0]

    for(var index in this.data.showList) {
      var item = this.data.showList[index]
      item.right = 0
    }
    this.setData({
      showList: this.data.showList,
      startX: touch.clientX,
    })

  },
  drawMove: function (e) {
    var touch = e.touches[0]
    var item = this.data.showList[e.currentTarget.dataset.index]
    var disX = this.data.startX - touch.clientX
    
    if (disX >= 20) {
      if (disX > this.data.delBtnWidth) {
        disX = this.data.delBtnWidth
      }
      item.right = disX
      this.setData({
        isScroll: false,
        showList: this.data.showList
      })
    } else {
      item.right = 0
      this.setData({
        isScroll: true,
        showList: this.data.showList
      })
    }
  },
  drawEnd: function (e) {
    var item = this.data.showList[e.currentTarget.dataset.index]
    if (item.right >= this.data.delBtnWidth/6) {
      item.right = this.data.delBtnWidth
      this.setData({
        isScroll: true,
        showList: this.data.showList,
      })
    } else {
      item.right = 0
      this.setData({
        isScroll: true,
        showList: this.data.showList,
      })
    }
    var tmpshowText = ''
    if (item.backup != '') {
      if (typeof (item.backup) != 'undefined') {
        tmpshowText = item.backup
      }
    } else {
      tmpshowText = ''
    }
    this.setData({
      listIndex: e.currentTarget.dataset.index,
      showText: tmpshowText,
      curbackup: tmpshowText
    })
  },

  backup: function (e) {
    var that = this
    util.NetStatusOk().then(function () {
      that.showDialogBtn(e)
    })
  },

  delItem: function (e) {
    var that = this

    wx.showModal({
      title: '提示',
      content: '是否确定删除' + `${that.data.text}`,
      success(res) {
        if (res.confirm) {
          util.NetStatusOk().then(function(){
            that.delCode()
          })
        } else if (res.cancel) {
          
        }
      }
    })
    return
    /** 蓝牙 */
    var trueIndex = that.data.showList[that.data.listIndex].trueIndex
    var tmpList = that.data.showList
    tmpList.splice(that.data.listIndex, 1)
    that.setData({
      showList: tmpList
    })
    /**实际发送接收需要设计消息队列，验证序列号一致 */
    var type = [0x02, 0x01, 0x03]
    var content = []
    content[0] = 0xff
    content[1] = 0xff
    content[2] = 0xff
    content[3] = 0xff
    content[4] = 0x02
    content[5] = type[that.data.devIndex]
    content[6] = trueIndex

    app.SendMsg(0x05, content, 0x0001)
    that.data.devInfo.deviceInfo[that.data.devIndex].usedNum--
    that.data.devInfo.deviceInfo[that.data.devIndex].detailInfo[trueIndex] = {
      data: 0,
      backup: ''
    }
    wx.setStorageSync('deviceInfo', that.data.devInfo)

  },

  delCode: function () {
    var that = this
    var trueIndex = that.data.showList[that.data.listIndex].trueIndex
    var tmpList = that.data.showList
    

    /** wifi*/
    const params = {
      url: 'https://api.link.aliyun.com/thing/device/service/invoke',
      apiVer: '1.1.2',
      param: {
        // 接口参数
        "productKey": that.data.productKey,
        "deviceName": that.data.deviceName,
        "inputParams": {
          KeyID: trueIndex.toString(),
          LockType: parseInt(that.data.devIndex)+1
        },
        "method": "DeleteKey",
      }
      
    }
    return new Promise(function (resolve, reject) {
      aliyun_api.request(params).then(function (res) {
        console.log(11111111)
        setTimeout(function(){
          console.log(222222222)
          that.getLockKeys().then(result => {
            console.log(4444444)
            console.log(result)
            if(result){
              tmpList.splice(that.data.listIndex, 1)
              console.log(that.data.devIndex, res)
              that.setData({
                showList: tmpList
              })
              console.log(that.data.showList)
              if (that.data.showList.length == 0) {
                console.log("kong ")
                that.setData({
                  default: true
                })
              }
              wx.showToast({
                title: '删除成功',
                icon: 'none',
                duration: 2000
              })
            }
            else{
              wx.showToast({
                title: '删除失败',
                icon: 'none',
                duration: 2000
              })
            }
        });
        },2000) 
      })
      .catch(function (res) {
        console.log(res)
        wx.showToast({
          title: '删除失败，请检查网络',
          icon: 'none',
          duration: 2000
        })
      })
    })
  },


  /***************************获取门锁钥匙*************************/
  getLockKeys: function () {
    console.log(33333333333)
    var that = this;
    const params = {
      url: 'https://api.link.aliyun.com/thing/device/property/query',
      apiVer: '1.1.2',
      param: {
        // 接口参数
        "productKey": that.data.productKey,
        "deviceName": that.data.deviceName,
        "propertyIdentifier": "LockKeys"
      }
    }
    return new Promise(function (resolve, reject) {
      aliyun_api.request(params).then(function (res) {
        console.log(that.data.showList)
        var keys = res.data.value;
        var trueIndex = that.data.showList[that.data.listIndex].trueIndex
        var lockType = parseInt(that.data.devIndex) + 1
        var isDel = true;
        for(let i = 0; i < keys.length; i++){
          if ((keys[i].T == lockType) && (keys[i].K == trueIndex.toString())){
            isDel = false;
            break;
          }
        }
        resolve(isDel)
      })
    })
  },


  /**
   * 弹窗
   */
  showDialogBtn: function (e) {
    var index = e.currentTarget.dataset.index
    var tmpcolor
    if (this.data.showText != '') {
      tmpcolor = '#ec5300'
    } else {
      tmpcolor = '#f0f0f0'
    }
    this.setData({
      showModal: true,
      color: tmpcolor
    })
  },
  /**
   * 弹出框蒙层截断touchmove事件
   */
  preventTouchMove: function () {},
  /**
   * 隐藏模态对话框
   */
  hideModal: function () {
    this.setData({
      showModal: false
    })
  },
  /**
   * 对话框取消按钮点击事件
   */
  onCancel: function () {
    this.hideModal()
  },
  /**
   * 对话框确认按钮点击事件
   */
  onConfirm: function () {
    if (this.data.color == 'f0f0f0') {
      return
    }
    if (this.data.curbackup != '') {
      var item = this.data.showList[this.data.listIndex]
      item.backup = this.data.curbackup
      this.setData({
        showList: this.data.showList
      })
      var trueIndex = this.data.showList[this.data.listIndex].trueIndex
      this.data.devInfo.deviceInfo[this.data.devIndex].detailInfo[trueIndex] = {
        data: 1,
        backup: item.backup
      }
      wx.setStorageSync('deviceInfo', this.data.devInfo)
      var tmpdevInfo = wx.getStorageSync('deviceInfo')
      console.log('保存成功', tmpdevInfo)
      this.hideModal()
    }
    /**利用门锁钥匙属性中的nickName增加备注，判断调用结果，弹窗提示 */
    
  },
  /**
   * 获取输入的密码
   */
  inputChange: function (e) {
    var val = e.detail.value
    if (val != '') {
      this.setData({
        color: '#ec5300'
      })
    } else {
      this.setData({
        color: '#f0f0f0'
      })
    }
    this.setData({
      curbackup: val
    })
  },
})